<template>
  <div class="ai-practice-container">
    <!-- 左侧历史对话记录 -->
    <div class="history-panel">
      <div class="new-chat-container">
        <button class="new-chat-btn" @click="newConversation">
          新建对话
          <el-icon class="plus-icon">
            <Plus/>
          </el-icon>
        </button>
      </div>
      <ul class="history-list">
        <li v-for="(item, index) in historyList" :key="index" @click="selectConversation(index)"
            :class="{ active: currentConversationIndex === index }">
          {{ item.title }}
        </li>
      </ul>
    </div>

    <!-- 右侧对话页面 -->
    <div class="chat-wrapper">
      <div class="chat-panel">
        <!-- 上半部分聊天界面 -->
        <div class="chat-messages" ref="chatMessagesRef">
          <div v-for="(message, index) in currentConversation.messages" :key="index" :class="['message', message.role]">
            <div class="avatar">
              <div v-if="message.role !== 'user'" class="ai-avatar">
                <img src="@/assets/images/ai.svg" alt="AI Avatar">
              </div>
              <div v-else>
                <img src="@/assets/avatar.jpeg" alt="Me">
              </div>
            </div>
            <div class="content" v-html="renderMarkdown(message.content)"></div>
          </div>
        </div>

        <!-- 输入框 -->
        <div class="input-area">
          <div class="input-wrapper">
            <el-upload
              ref="upload"
              sty
              class="upload-demo"
              action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
              :limit="1"
              :on-exceed="handleExceed"
              :auto-upload="false"
            >
              <el-icon class="input-icon link-icon">
                <Link/>

              </el-icon>
            </el-upload>

            <input
              v-model="userInput"
              @keydown="handleKeydown"
              placeholder="输入消息，回车发送（Shift+Enter换行）"
              :disabled="isInputDisabled"
              type="text"
            />
            <div class="button-group">
              <div class="audio-wave" v-if="isRecording" @click="finishRecording">
                <span v-for="n in 4" :key="n" :style="{ animationDelay: `${n * 0.2}s` }"></span>
              </div>
              <el-icon v-else class="input-icon microphone-icon" @click="toggleRecording">
                <Microphone/>
              </el-icon>
              <div class="separator"></div>
              <el-popover
                placement="top"
                :width="200"
                trigger="hover"
                :disabled="!!userInput.trim()"
              >
                <template #reference>
                  <el-button
                    class="send-button"
                    circle
                    @click="sendMessage"
                    :disabled="!userInput.trim()"
                  >
                    <el-icon>
                      <Top/>
                    </el-icon>
                  </el-button>
                </template>
                <span>请文字/录音/上传语音回复</span>
              </el-popover>
            </div>
          </div>
        </div>

        <div class="disclaimer">
          服务生成的所有内容均由魔法海螺生成，其生成内容的准确性和完整性无法保证，不代表UP主的态度或观点
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, nextTick, onMounted, onUnmounted, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { API } from '@/api/config';
import { BASE_URL_OLLAMA } from '../../../api/config';
import { marked } from 'marked';
import hljs from 'highlight.js';
import 'highlight.js/styles/github.css';

// 配置 marked
marked.setOptions({
  highlight: (code, language) => {
    const validLanguage = hljs.getLanguage(language) ? language : 'plaintext';
    return hljs.highlight(code, { language: validLanguage }).value;
  },
});

// 将 Markdown 解析为 HTML
const renderMarkdown = (content) => {
  const html = marked(content);
  // 为代码块添加行号
  return html.replace(/<pre><code class="language-(\w+)">([\s\S]*?)<\/code><\/pre>/g, (match, lang, code) => {
    const highlightedCode = hljs.highlight(code, { language: lang }).value;
    const lines = highlightedCode.split('\n');
    const numberedCode = lines
      .map((line, index) => `<span class="line">${line}</span>`)
      .join('\n');
    return `<pre><code class="language-${lang}">${numberedCode}</code></pre>`;
  });
};


const controller = ref(null);
const historyList = ref([
  {
    title: '蟹堡制作咨询',
    messages: [
      { role: 'assistant', content: '您好！我是蟹堡王的神奇海螺，很高兴为您服务！我可以回答关于蟹堡王和汉堡制作的任何问题，您有什么需要帮助的吗？' },
      { role: 'user', content: '是的，我的蟹堡总是做不好，口感跟海绵宝宝做的差太多了。' },
      {
        role: 'assistant',
        content: '别担心！让我来帮您分析一下。首先，您是否严格按照蟹堡秘方的比例在调配调味料呢？另外，确保使用新鲜的海藻面包也很重要。'
      }
    ]
  },
  // 其他对话记录...
]);

const currentConversationIndex = ref(0);
const userInput = ref('');
const isListening = ref(false);
const chatMessagesRef = ref(null);
const isRecording = ref(false);
let mediaRecorder = null;
let audioChunks = [];
const mediaStream = ref(null);
const isInputDisabled = ref(false);
const textareaRef = ref(null);

// 动态调整 textarea 高度
const adjustTextareaHeight = () => {
  const textarea = textareaRef.value;
  textarea.style.height = 'auto'; // 重置高度
  textarea.style.height = `${textarea.scrollHeight}px`; // 根据内容调整高度
};

// 监听 userInput 的变化
watch(userInput, () => {
  nextTick(() => {
    adjustTextareaHeight();
  });
});
const currentConversation = computed(() => historyList.value[currentConversationIndex.value]);

const selectConversation = (index) => {
  currentConversationIndex.value = index;
  nextTick(() => {
    scrollToBottom();
  });
};

const newConversation = () => {
  historyList.value.unshift({
    title: '新对话',
    messages: [{
      role: 'assistant',
      content: '您好！我是蟹堡王的神奇海螺，很高兴为您服务！我可以回答关于蟹堡王和汉堡制作的任何问题，您有什么需要帮助的吗？'
    }]
  });
  currentConversationIndex.value = 0;
};

const sendMessage = async () => {
  if (userInput.value.trim()) {
    controller.value = new AbortController();
    currentConversation.value.messages.push({ role: 'user', content: userInput.value });
    const prompt = userInput.value;
    userInput.value = '';
    nextTick(() => {
      scrollToBottom();
    });

    const loadingMessage = { role: 'assistant', content: '神奇海螺正在思考...', loading: true };
    currentConversation.value.messages.push(loadingMessage);
    nextTick(() => {
      scrollToBottom();
    });

    try {
      const response = await fetch(`${BASE_URL_OLLAMA}${API.OLLAMACHAT}`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          model: 'deepseek-r1:8b',
          messages: [{ role: 'user', content: prompt }],
          stream: true,
        }),
        signal: controller.value.signal,
      });

      const reader = response.body.getReader();
      const decoder = new TextDecoder('utf-8');
      let done = false;
      let aiResponse = '';
      let accumulatedContent = '';

      while (!done) {
        const { value, done: readDone } = await reader.read();
        done = readDone;
        const chunk = decoder.decode(value, { stream: true });
        aiResponse += chunk;

        const messages = chunk.split('\n').filter(Boolean);
        messages.forEach(message => {
          try {
            const aiMessage = JSON.parse(message);
            accumulatedContent += aiMessage.message.content;
          } catch (error) {
            console.error('Failed to parse message:', message);
          }
        });

        currentConversation.value.messages.pop();
        currentConversation.value.messages.push({ role: 'assistant', content: accumulatedContent });
        nextTick(() => {
          scrollToBottom();
        });
      }

      if (aiResponse && !done) {
        currentConversation.value.messages.pop();
        currentConversation.value.messages.push({ role: 'assistant', content: aiResponse });
        nextTick(() => {
          scrollToBottom();
        });
      }
    } catch (error) {
      console.error('sendMessage error', error);
      ElMessage.error('获取回复失败，请稍后重试');
      currentConversation.value.messages.pop();
      loadingMessage.content = '获取回复失败，请稍后重试';
      loadingMessage.loading = false;
      currentConversation.value.messages.push(loadingMessage);
      nextTick(() => {
        scrollToBottom();
      });
    }
  }
};

const handleKeydown = (e) => {
  if (e.key === 'Enter' && !e.shiftKey) {
    // 按下 Enter（没有 Shift）：发送消息
    e.preventDefault(); // 阻止默认换行行为
    sendMessage();
  } else if (e.key === 'Enter' && e.shiftKey) {
    // 按下 Shift + Enter：换行
    e.preventDefault(); // 阻止默认发送行为
    userInput.value += '\n'; // 添加换行符
  }
};

const scrollToBottom = () => {
  const chatMessages = chatMessagesRef.value;
  chatMessages.scrollTop = chatMessages.scrollHeight;
};

onMounted(() => {
});

onUnmounted(() => {
  finishRecording();
  stopMediaStream();
});
</script>

<style scoped>
/* 样式保持不变 */
.ai-practice-container {
  display: flex;
  height: calc(100vh - 10% - 70px);
  font-family: Arial, sans-serif;
}

.history-panel {
  width:180px;
  background: linear-gradient(135deg, rgba(230, 240, 255, 0.01), rgba(240, 230, 255, 0.01));
  background-color: #ffffff;
  padding: 20px;
  overflow-y: auto;
}

.new-chat-container {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.new-chat-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  padding: 13px; /* 略微增加内边距 */
  margin-top: 10px;
  margin-bottom: 5px;
  background: linear-gradient(to right, #0069e0, #0052bc); /* 改用更深的蓝色渐变 */
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: opacity 0.3s;
  font-size: 14px; /* 加大字号 */
  font-weight: bold; /* 加粗字体 */
}

.new-chat-btn:hover {
  opacity: 0.9;
}

.history-list {
  list-style-type: none;
  padding: 0;
}

.history-list li {
  padding: 10px;
  margin-bottom: 10px;
  background-color: #ffffff;
  border-radius: 8px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.history-list li:hover,
.history-list li.active {
  background-color: rgba(0, 105, 224, 0.15);
  color: #0052bc;
}

.chat-wrapper {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg,
  rgba(0, 105, 224, 0.08),
  rgba(0, 56, 148, 0.08)
  );
}

.chat-panel {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: transparent;
  box-shadow: none;
  padding-top: 12px; /* 添加顶部内边距 */
  /* padding-left: 10%;
  padding-right: 10%; */
}

.visitor-info {
  background-color: transparent; /* 背透明 */
  padding: 15px 20px; /* 增加内边距 */
  margin-bottom: 20px; /* 增加与第一条对话的距离 */
  font-weight: bold;
  color: #333;
  text-align: left;
  font-size: 18px; /* 增大字体大小 */
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding-top: 20px;
  padding-left: 10%;
  padding-right: 10%;
  background-color: transparent;
  /* 修改滚动条颜色 */
  scrollbar-width: thin;
  scrollbar-color: rgba(0, 105, 224, 0.3) transparent;
}

/* 为 Webkit 浏览器（如 Chrome、Safari）自定义滚动条样式 */
.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.chat-messages::-webkit-scrollbar-track {
  background: transparent;
}

.chat-messages::-webkit-scrollbar-thumb {
  background-color: rgba(0, 105, 224, 0.3);
  border-radius: 3px;
}

.message {
  display: flex;
  margin-bottom: 20px;
}

.message .avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #ffffff;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 10px;
  overflow: hidden;
}

.message .avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 50%;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #ffffff;
}

.message .content {
  background-color: rgba(255, 255, 255, 1);
  padding: 12px 18px; /* 增加内边距 */
  border-radius: 10px;
  max-width: 80%;
  font-size: 16px; /* 增加字体大小 */
  line-height: 1.8; /* 增加行高 */
}

.message.user {
  flex-direction: row-reverse;
}

.message.user .avatar {
  margin-right: 0;
  margin-left: 10px;
}

.message.user .content {
  background-color: rgba(0, 105, 224, 0.12);
  color: black;
}

.input-area {
  padding: 20px 10% 0 10%;
  border-top: 0px solid #e0e0e0;
  background-color: transparent;
}

.input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}
input {
  width: 100%;
  padding: 12px 120px 12px 50px; /* 调整右侧padding以适应新的按钮组 */
  border: 1px solid rgba(204, 204, 204, 0.5);
  border-radius: 25px;
  font-size: 16px;
  background-color: rgba(255, 255, 255, 0.7);
  transition: border-color 0.3s;
  height: 55px;
}

input:focus {
  outline: none;
  border-color: #0069e0;
}

input::placeholder {
  color: #969696;
}

.button-group {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  display: flex;
  align-items: center;
}

.input-icon {
  color: #0069e0;
  font-size: 24px;
  cursor: pointer;
}

.link-icon {
  position: absolute;
  left: 18px;
  top: 50%;
  transform: translateY(-50%);
}
.input-icon.link-icon {
  position: absolute;
  left: 12px; /* 调整图标与输入框左侧的距离 */
  top: 50%;

  transform: translateY(-50%);
  z-index: 1;
  color: #0069e0;
  font-size: 24px;
}

.microphone-icon {
  margin-right: 0; /* 将右侧边距改为0 */
}

.separator {
  width: 1px;
  height: 25px;
  background-color: rgba(204, 204, 204, 0.5);
  margin: 0 10px;
}

.send-button {
  width: 40px;
  height: 40px;
  background: linear-gradient(to right, #0069e0, #0052bc); /* 保持一致的蓝色渐变 */
  border: none;
  color: white;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
}

.send-button:disabled {
  background: rgba(0, 105, 224, 0.1);
  color: rgba(0, 82, 188, 0.3);
  cursor: default;
}

.send-button :deep(.el-icon) {
  font-size: 24px;
}

.send-button:not(:disabled):hover {
  opacity: 0.9;
}

/* 新增的免责声明样式 */
.disclaimer {
  font-size: 10px;
  color: #999;
  text-align: center;
  margin-top: 12px;
  margin-bottom: 12px;
}

.audio-wave {
  display: flex;
  align-items: center;
  height: 24px;
  width: 24px;
}

.audio-wave span {
  display: inline-block;
  width: 3px;
  height: 100%;
  margin-right: 1px;
  background: #0069e0;
  animation: audio-wave 0.8s infinite ease-in-out;
}

@keyframes audio-wave {
  0%, 100% {
    transform: scaleY(0.3);
  }
  50% {
    transform: scaleY(1);
  }
}

.message .content audio {
  margin-top: 10px;
  width: 100%;
}
.el-input {
  width: 100%;
  height: 80px;
  padding: 12px 110px 12px 50px; /* 调整右侧 padding 以适应按钮组 */
  border: 1px solid rgba(204, 204, 204, 0.5);
  border-radius: 50px;
  font-size: 16px;
  background-color: rgba(255, 255, 255, 0.7);
  transition: border-color 0.3s;
  resize: none; /* 禁止手动调整大小 */
  overflow: hidden; /* 隐藏滚动条 */
  line-height: 1.5; /* 设置行高 */
  outline: none;
}

.el-input:focus {
  outline: none;
  border-color: #0069e0;
}

.el-input::placeholder {
  color: #1a1a1a;
}
/* 代码块样式 */
pre {
  background-color: #f6f8fa; /* 代码块背景色 */
  padding: 12px;
  border-radius: 6px;
  overflow-x: auto; /* 横向滚动 */
  font-size: 14px;
  line-height: 1.5;
  margin: 10px 0;
  position: relative;
}

code {
  font-family: 'Courier New', Courier, monospace;
  color: #d63384; /* 代码颜色 */
}

/* 高亮样式 */
.hljs {
  background-color: transparent; /* 高亮背景透明 */
}

/* 行号样式 */
pre code {
  counter-reset: line;
}

pre code .line::before {
  counter-increment: line;
  content: counter(line);
  display: inline-block;
  width: 2em; /* 行号宽度 */
  padding-right: 1em;
  margin-right: 1em;
  color: #999; /* 行号颜色 */
  text-align: right;
  user-select: none; /* 禁止选中行号 */
}
</style>
